import { login, logout, getInfo } from '@/api/user';
import {
  getToken,
  setToken,
  removeToken,
  removeRole,
  removeIORG,
  removeUserID,
  getRoleInfo,
  getUserInfo,
  setName,
  getName,
  getIRole,
  setIRole,
  SET_IORG,
  GET_IORG,
  setUserID,
  getUserID
} from '@/utils/auth';
import router, { resetRouter } from '@/router';
import md5 from 'js-md5';
import { constantRoutes } from '@/router/index';

const state = {
  token: getToken(),
  name: getName(),
  roleInfo: getRoleInfo(),
  roles: [],
  init: false, // 是否完成初始化 // 默认未完成
  RouterList: [], // 动态路由
  routes: [],
  addRoutes: [],
  userInfo: getUserInfo(),
  iRolesysnum: getIRole(),
  iOrgsysnum: GET_IORG(), // 机构编号
  userId: getUserID() // 用户ID
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERID: (state, userId) => {
    state.userId = userId;
  },

  SET_ROLEINFO: (state, roleInfo) => {
    state.roleInfo = roleInfo;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },

  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  set_router: (state, RouterList) => {
    state.RouterList = RouterList;
  },
  set_init: (state, status) => {
    state.init = status;
  },
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes;
    state.routes = constantRoutes.concat(routes);
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
  IROLESYSNUM: (state, iRolesysnum) => {
    state.iRolesysnum = iRolesysnum;
  },
  IORGSYSNUM: (state, iOrgsysnum) => {
    state.iOrgsysnum = iOrgsysnum;
  }
};

const actions = {
  // 登录
  login({ commit }, userInfo) {
    const { strUsernum, strPassword } = userInfo;
    return new Promise((resolve, reject) => {
      login({
        strUsernum: strUsernum.trim(),
        strPassword: md5(strPassword)
      })
        .then(res => {
          const { strTokenid, strUserid } = res.data;
          console.log(strTokenid, strUserid);
          commit('SET_TOKEN', strTokenid);
          setToken(strTokenid);
          // commit('SET_USERID', strUserid);
          // setUserID(strUserid);
          // store.dispatch('user/getInfo');
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { roleData, userData } = response;

          if (!userData) {
            reject('验证失败，请重新登录');
          }

          const { iOrgsysnum, strUsername, iUsersysnum } = userData;

          commit('SET_NAME', strUsername);
          setName(strUsername);

          commit('IROLESYSNUM', roleData[0].iRolesysnum);
          setIRole(roleData[0].iRolesysnum);

          commit('IORGSYSNUM', iOrgsysnum);
          SET_IORG(iOrgsysnum);

          // 新增接口所需参数 用户ID
          commit('SET_USERID', iUsersysnum);
          setUserID(iUsersysnum);

          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // 前端退出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          resetRouter();

          commit('SET_TOKEN', '');
          commit('SET_ROLES', []);
          commit('set_router', []);
          commit('set_init', false);
          commit('SET_USERID', '');
          removeRole();
          removeIORG();
          removeToken();
          removeUserID();

          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '');
      commit('SET_ROLES', []);
      removeToken();
      resolve();
    });
  },

  // 动态设置路由 此为设置设置途径
  setRouterList({ commit }, routerList) {
    commit('set_router', constantRoutes.concat(routerList)); // 进行路由拼接并存储
    // commit("set_router", routerList); // 进行路由拼接并存储
  },
  // 存储权限
  setroles({ commit }, roleList) {
    commit('SET_ROLES', roleList);
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token';
      commit('SET_TOKEN', token);
      setToken(token);
      const { roles } = await dispatch('getInfo');
      resetRouter();
      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      });
      // dynamically add accessible routes
      router.addRoutes(accessRoutes);
      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true });
      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
